package com.etymgiko.spaceshipshop.web;

import com.etymgiko.spaceshipshop.model.User;
import com.etymgiko.spaceshipshop.service.UserManager;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Login action.
 *
 * @author Ivan Holub
 */
public class LoginAction extends Action {

    private UserManager userManager;

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        // Get the existing session.
        HttpSession session = httpServletRequest.getSession(false);
        // Invalidate the existing session. 
        if (session != null) {
            session.invalidate();
        }

        LoginForm form = (LoginForm) actionForm;

        String login = form.getUsername();
        String password = form.getPassword();

        User user = userManager.findUser(login, password);
        if (user == null) {
            ActionMessages errors = new ActionMessages();
            errors.add("name", new ActionMessage("errors.login.error"));
            saveErrors(httpServletRequest, errors);
            return actionMapping.findForward("error");
        }

        // Create a new session for the user. 
        httpServletRequest.getSession(true).setAttribute("user", user);

        return actionMapping.findForward("success");
    }
}

